package yunjiao.javatutorials.guava.concurrent.transform.assembly;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 流水线处理
 *
 * @author yangyunjiao
 */
public class TransformFutureDemo {
    public static void main(String[] args) throws Exception {
        OrderProcessingService orderService = new OrderProcessingService();
        ImageProcessingService imageService = new ImageProcessingService();
        DataAggregationService dataService = new DataAggregationService();

        // 处理订单
        ListenableFuture<OrderResult> orderFuture = orderService.processOrderAsync("order-123");
        Futures.addCallback(orderFuture, new FutureCallback<OrderResult>() {
            @Override
            public void onSuccess(OrderResult result) {
                System.out.println("订单处理成功: " + result.orderId() +
                        ", 金额: " + result.totalAmount());
            }

            @Override
            public void onFailure(Throwable t) {
                System.err.println("订单处理失败: " + t.getMessage());
            }
        }, MoreExecutors.directExecutor());

        // 处理图片
        ListenableFuture<ProcessedImage> imageFuture =
                imageService.processImageWithFallbackAsync("https://example.com/image.jpg");

        // 获取用户档案
        ListenableFuture<UserProfile> profileFuture =
                dataService.getUserProfileWithTimeoutAsync("user123");

        // 等待所有任务完成
        ListenableFuture<List<Object>> allFutures = Futures.allAsList(
                orderFuture, imageFuture, profileFuture
        );

        List<Object> results = allFutures.get(5, TimeUnit.SECONDS);
        System.out.println("所有异步任务完成");
    }
}
